const g = getApp().globalData
const util = g.util

let choose_year = null,
    choose_month = null;

Page({
    data: {
        hasEmptyGrid: false,
        days: []
    },

    onLoad(options) {
        let id = options.id
        this.id = id
        this.name = options.name
        this.getMonthReport(id)
        this.calendarInit()
    },

    //获取开关月报
    getMonthReport(id) {
        let url = `switchs/monthReport?id=${id}`
        util.httpGet({
            url: url,
            header: { authorization: g.userInfo.token },
            fn: res => {
                if (res == 'refreshToken') {
                    this.getMonthReport(id)
                    return
                }
                console.log('monthReport', res.data.result)
                let days = this.data.days
                days = this.processDataWithRes(days, res.data.result)
                this.setData({
                    days
                })

            }
        })
    },

    processDataWithRes(days, res) {
        if (days.length == res.length) {
            for (let i in days) {
                days[i].choosed = res[i].light == 1
                days[i].date = res[i].date
            }

        }
        return days
    },

    // 跳转到操作日志
    goOperateLog(e) {
        let date = e.currentTarget.dataset.date
        wx.navigateTo({
            url: `../operateLog/operateLog?id=${this.id}&date=${date}&name=${this.name}`,
        })
    },



    //日志初始化
    calendarInit() {
        const date = new Date();
        const cur_year = date.getFullYear();
        const cur_month = date.getMonth() + 1;
        const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
        this.calculateEmptyGrids(cur_year, cur_month);
        this.calculateDays(cur_year, cur_month);
        this.setData({
            cur_year,
            cur_month,
            weeks_ch
        });
    },

    getThisMonthDays(year, month) {
        return new Date(year, month, 0).getDate();
    },
    getFirstDayOfWeek(year, month) {
        return new Date(Date.UTC(year, month - 1, 1)).getDay();
    },
    calculateEmptyGrids(year, month) {
        const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
        let empytGrids = [];
        if (firstDayOfWeek > 0) {
            for (let i = 0; i < firstDayOfWeek; i++) {
                empytGrids.push(i);
            }
            this.setData({
                hasEmptyGrid: true,
                empytGrids
            });
        } else {
            this.setData({
                hasEmptyGrid: false,
                empytGrids: []
            });
        }
    },
    calculateDays(year, month) {
        let days = [];

        const thisMonthDays = this.getThisMonthDays(year, month);

        for (let i = 1; i <= thisMonthDays; i++) {
            days.push({
                day: i,
                choosed: false
            });
        }

        this.setData({
            days
        });
    },
})
